﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Linq;

namespace G.Controls
{
    public class DynamicTemplateListBox : ListBox
    {
        public static readonly DependencyProperty DataTemplateDataTagProperty = DependencyProperty.RegisterAttached("DataTemplateDataTag", typeof(int), typeof(DynamicTemplateListBox), new PropertyMetadata(0));


        public static int GetDataTemplateDataTag(DataTemplate element)
        {
            return (int)element.GetValue(DynamicTemplateListBox.DataTemplateDataTagProperty);
        }

        public static void SetDataTemplateDataTag(DataTemplate element, int value)
        {
            element.SetValue(DynamicTemplateListBox.DataTemplateDataTagProperty, value);
        }

        public static readonly DependencyProperty DataTypesProperty = DependencyProperty.Register("DataTypes", typeof(List<DataTemplate>), typeof(DynamicTemplateListBox), null);

        public List<DataTemplate> DataTypes
        {
            get
            {
                return this.GetValue(DynamicTemplateListBox.DataTypesProperty) as List<DataTemplate>;
            }
            set
            {
                this.SetValue(DynamicTemplateListBox.DataTypesProperty, value);
            }
        }

        public DynamicTemplateListBox()
        {
            this.DataTypes = new List<DataTemplate>();
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            G.Data.IDynamicTemplate gridItemSize = item as G.Data.IDynamicTemplate;
            ContentControl gridViewItem = element as ContentControl;
            if (gridItemSize != null)
            {
                //如果tag不为0，那么表示需要使用默认模板以外的模版
                if (gridItemSize.Tag == 0)
                {
                    base.PrepareContainerForItemOverride(element, item);
                }
                else
                {
                    //获取tag对应的模版
                    var a = this.DataTypes.FirstOrDefault(c => DynamicTemplateListBox.GetDataTemplateDataTag(c) == gridItemSize.Tag);
                    if (a == null)
                    {
                        base.PrepareContainerForItemOverride(element, item);
                    }
                    else
                    {
                        base.PrepareContainerForItemOverride(element, item);
                        //将模版赋值给gridViewItem
                        gridViewItem.ContentTemplate = a;
                    }
                }
            }
            else
                base.PrepareContainerForItemOverride(element, item);
        }
    }
}
